package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.admin.AdminOrderMapper;
import com.sky.pojo.Orders;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.AdminOrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;


@Service
@Slf4j
public class AdminOrderServiceImpl implements AdminOrderService {
    @Autowired
    private AdminOrderMapper adminOrderMapper;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Override
    public Result<PageResult> selectOrderList(OrdersPageQueryDTO orderDto) {
        PageHelper.startPage(orderDto.getPage(),orderDto.getPageSize());
        List<OrderVO> list = adminOrderMapper.selectOrder(orderDto);
        PageInfo<OrderVO> info = new PageInfo<>(list);
        PageResult result = new PageResult(info.getTotal(),info.getList());
        return Result.success(result);
    }

    @Override
    public OrderStatisticsVO selectStatistis() {
     /*   //这里可以用线程池进行优化：
        //普通的查询需要一个线程去数据库中查找六次，但线程池技术，可以每个线程去数据库查找一次，
        *//*Integer waiting4MerchantReceiveOrders = adminOrderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer waitng4RiderReceiveOrders = adminOrderMapper.countStatus(Orders.CONFIRMED);
        Integer toBeDeliveryOnProgressOrders = adminOrderMapper.countStatus(Orders.TOBEDELIVERED);
        Integer toBeArrivedOrders = adminOrderMapper.countStatus(Orders.TOBEDELIVERED);
        Integer completedOrders = adminOrderMapper.countStatus(Orders.COMPLETE_ORDER);
        Integer canceledOrders = adminOrderMapper.countStatus(Orders.CANCELLED_ORDER);*//*

        Future<Integer> future1 = threadPoolExecutor.submit(() -> {
            return orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        });
        Future<Integer> future2 = threadPoolExecutor.submit(() -> {
            return orderMapper.countStatus(Orders.CONFIRMED);
        });
        Future<Integer> future3 = threadPoolExecutor.submit(() -> {
            return orderMapper.countStatus(Orders.TOBEDELIVERED);
        });
        Future<Integer> future4 = threadPoolExecutor.submit(() -> {
            return orderMapper.countStatus(Orders.TOBEDELIVERED);
        });
        Future<Integer> future5 = threadPoolExecutor.submit(() -> {
            return orderMapper.countStatus(Orders.COMPLETE_ORDER);
        });
        Future<Integer> future6 = threadPoolExecutor.submit(() -> {
            return orderMapper.countStatus(Orders.CANCELLED_ORDER);
        });

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .waiting4MerchantReceiveOrders(future1)//  status = 2  等待商家接单
                .waitng4RiderReceiveOrders(future2)//  status = 3  等待骑手接单
                .toBeDeliveryOnProgressOrders(future3)//  status = 4  待出货订单数
                .toBeArrivedOrders(future4)//  status = 5  待送达订单数
                .completedOrders(future5) // status = 6  已完成订单数
                .canceledOrders(future6)//  status = 7  已取消订单数
                .build();
        return orderStatisticsVO;*/

        //未优化：
        OrderStatisticsVO statisticsVO = adminOrderMapper.selectOrderStatistis();
        return statisticsVO;
    }

    @Override
    public Result<OrderVO> selectOrderInfo(Long orderId) {
        OrderVO orderVO = adminOrderMapper.selectOrderInfo(orderId);
        return Result.success(orderVO);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        //修改订单数据
        Orders orders = adminOrderMapper.selectOrderInfo(ordersCancelDTO.getId());
        if(orders.getStatus()==1||orders.getStatus()==6||orders.getStatus()==7||orders.getStatus()==8){
            throw new RuntimeException("-------订单状态不正确，无法取消-------");
        }

        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLING);  //状态8，取消中，等待退款成功
        adminOrderMapper.updateCancellingOrder(orders.getStatus(),orders.getNumber());
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id查询订单
        Orders ordersDB = adminOrderMapper.selectOrderInfo(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            log.info("申请退款：{}");
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();

        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED_ORDER);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        adminOrderMapper.update(orders);
    }
}
